package com.larson.creator.view
{
	import com.larson.creator.ApplicationFacade;
	import com.larson.creator.model.*;
	import com.larson.creator.model.vo.*;
	import com.larson.creator.view.components.*;
	import com.mapquest.*;
	import com.mapquest.tilemap.*;
	import com.mapquest.tilemap.controls.*;
	import com.mapquest.tilemap.overlays.LineOverlay;
	import com.mapquest.tilemap.pois.*;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.events.ResizeEvent;
	
	import org.puremvc.as3.interfaces.*;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	public class mapMediator extends Mediator implements IMediator
	{
        // Cannonical name of the Mediator
        public static const NAME:String = "mapMediator";

		//private var fileConvertProxy:FileConvertProxy;  
        private var _mqMap:TileMap; 
        
        private var rActive:Boolean = false;
		
		        
        /**
         * Constructor. 
         */
		public function mapMediator (viewComponent:mapScreen)
		{
            // pass the viewComponent to the superclass where 
            // it will be stored in the inherited viewComponent property
            super( NAME, viewComponent );
            
            map.addEventListener(mapScreen.CREATE_MAP, this.createMap);
		}
		
		
        /**
         * List all notifications this Mediator is interested in.
         * <P>
         * Automatically called by the framework when the mediator
         * is registered with the view.</P>
         * 
         * @return Array the list of Nofitication names
         */
        override public function listNotificationInterests():Array 
        {

            return [ 
					ApplicationFacade.LOADING_STEP,
					ApplicationFacade.LOADING_COMPLETE,
					ApplicationFacade.DATA_READY

					];


        }

        /**
         * Handle all notifications this Mediator is interested in.
         * <P>
         * Called by the framework when a notification is sent that
         * this mediator expressed an interest in when registered
         * (see <code>listNotificationInterests</code>.</P>
         * 
         * @param INotification a notification 
         */
        override public function handleNotification( note:INotification ):void 
        {
            switch ( note.getName() ) 
			{
				
				case ApplicationFacade.DATA_READY:
					// Get the mapping data from the fileconversion proxy.
					// Get the convert data Proxy in order to acquire the data provider for our data grid.
					var fileLoadProxy:FileLoadProxy = ApplicationFacade.getFileLoadProxy();
					mapPoints(fileLoadProxy.rawData, fileLoadProxy.lineData);

					break;
					
				case ApplicationFacade.LOADING_COMPLETE:
					// all done
					// show the main screen
					this.sendNotification( ApplicationFacade.VIEW_BUILD_SCREEN );
					break;
					
				case ApplicationFacade.CONVERT_FILE_COMPLETE:				
					var loadProxy:FileLoadProxy = ApplicationFacade.getFileLoadProxy();
					var fileConvertProxy:FileConvertProxy = ApplicationFacade.getFileConvertProxy();
					mapPoints(loadProxy.rawData, fileConvertProxy.lineData);

					break;				
				/*	
					case ApplicationFacade.LOAD_RESOURCE_FAILED:
					// error reading the config XML fille
					// show the error
					this.splashScreen.errorText.text = note.getBody() as String;
					this.splashScreen.errorBox.visible = true;
					break;
				*/

            }
        }

        /**
         * Cast the viewComponent to its actual type.
         * 
         * <P>
         * This is a useful idiom for mediators. The
         * PureMVC Mediator class defines a viewComponent
         * property of type Object. </P>
         * 
         * <P>
         * Here, we cast the generic viewComponent to 
         * its actual type in a protected mode. This 
         * retains encapsulation, while allowing the instance
         * (and subclassed instance) access to a 
         * strongly typed reference with a meaningful
         * name.</P>
         * 
         * @return SplashScreen the viewComponent cast to org.puremvc.as3.demos.flex.appskeleton.view.components.SplashScreen
         */
		 
        protected function get map():mapScreen
		{
            return viewComponent as mapScreen;
        }
		

		private function mapPoints(points:ArrayCollection, lineData:ArrayCollection) :void {
			var idx:Number = 0;
			var len:Number = points.length;
			
			var lo:LineOverlay = new LineOverlay();
			var shapes:PointLLCollection = new PointLLCollection();
			var icons:ShapeCollection = new ShapeCollection("icons");
			var shapesArray:Array = new Array();
			// Embed the Icon in the Class
			[Embed (source="/images/orSquare.png")]
			var NyIcon:Class;
			
			map._mqMap.removeAllOverlays();
			map._mqMap.removeAllShapes();
            for (idx = 0; idx < len; idx++) {
            	var pt:CourseDataVO = points.getItemAt(idx) as CourseDataVO;
            	var ld:LineDataVO = lineData.getItemAt(idx) as LineDataVO;
            	var shape:PointLL = new PointLL(pt.latitude, pt.longitude);
             	shapes.addPointLL(shape);
             	shapesArray.push(shape);
             	
             	// Create a POI object and set it's location.
				var _myPoi:Poi = new Poi(shape);
             	
				// Set rollover and popup text.
				_myPoi.setInfoTitle("Slope: " + ld.slope.toString());
				//_myPoi.setInfoContent("Slope: " + pt.slope.toString());
				// A key value can be assigned to help you keep track of the poi's you put on the map.
				_myPoi.setKey("A" + idx.toString());
				// Create new icon object
				var _myIcon:MapIcon = new MapIcon();
				_myIcon.setImage(new NyIcon(),5,5);
				// Associate icon with POI
				_myPoi.setIcon(_myIcon);
				_myPoi.setMinZoomLevel(11);
				_myPoi.setMaxZoomLevel(16);
				// Add the Poi to the map.
				map._mqMap.addShape(_myPoi);			
							
             }
            
            lo.setBorderWidth(10);
            lo.setColor(0xFF0000);
            lo.setColorAlpha(0.4);
            lo.setShapePoints(shapes);
            //lo.addEventListener(MouseEvent.MOUSE_OVER, this.processRollover );
            //lo.addEventListener(MouseEvent.MOUSE_OUT, this.processRollout );
            map._mqMap.addOverlay(lo);
            map._mqMap.bestFitLL(shapesArray);
            
		}
		

		
		public function createMap(event:Event=null):void {
			
			var _zoomControl:ZoomControl = new ZoomControl();
			var _mapTypeControl:ViewControl = new ViewControl();
			
			map._mqMap.addControl(_zoomControl);
			map._mqMap.addControl(_mapTypeControl);

			map._mqMap.setCenter(new PointLL(43.0683060, -88.2603338));

			var lo:LineOverlay = new LineOverlay();
			var shapes:PointLLCollection = new PointLLCollection();	
			lo.setShapePoints(shapes);	
			map._mqMap.addOverlay(lo);
             
            map.addEventListener(ResizeEvent.RESIZE, handleContainerResize); 
            map._mqMap.addEventListener( TileMapEvent.ZOOM_END, zoomNotice );
            map._mqMap.useHandCursor = false;
            	

		}
		
		public function zoomNotice( te:TileMapEvent ):void {
			
			trace(te.zoom);
			
		}
		
        private function handleContainerResize(event:ResizeEvent):void {
            // set the size of the map based on its containers size.
            //_mqMap.setSize(new Size(map.mapContainer.width,map.mapContainer.height)); 
            map._mqMap.setSize(new Size(map.width,map.height));
        }
	}
}